# -*- encoding: utf-8 -*-
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.views.decorators.cache import cache_page

import datetime

from models import Schedule

@cache_page(15 * 60)
def schedule_day(request):
    schedule = request.section.day.get()
    concerts = schedule.concerts.all()#select_related().order('scene', 'starting_time')

    stacks = []
    current_scene = None
    current_stack = []

    DELAY = {'friday': {'start': 20, 'nb': 8},
             'saturday': {'start': 13, 'nb': 24},
             'sunday': {'start': 13.5, 'nb': 22},
             'monday': {'start': 13.5, 'nb': 22}}

    for s in concerts:
        if getattr(current_scene, 'id', None) != s.scene.id:
            if current_scene is not None:
                # Changement de scene
                stacks.append({'scene': current_scene, 'stack': current_stack})
            current_scene = s.scene

            last_schedule = Schedule()
            last_schedule.starting_time = datetime.time(hour=int(DELAY[concerts[0].day.day]['start']), minute=float(DELAY[concerts[0].day.day]['start'] - int(DELAY[concerts[0].day.day]['start'])) * 60)
            last_schedule.playing_time = 0

            current_stack = []
            
        if last_schedule is not None:
            # Ce n'est pas le premier concert de la scène
            time = (datetime.datetime.combine(datetime.date.today(), s.starting_time) - (datetime.datetime.combine(datetime.date.today(), last_schedule.starting_time) + datetime.timedelta(minutes=last_schedule.playing_time)))
            empty = {'colspan': time.seconds / 1800} # 60 seconds * 30 minutes = 1800
            current_stack.append(empty)
            
        s.colspan = s.playing_time / 30 # Une case = 30 minutes

        current_stack.append(s)

        last_schedule = s
        
    stacks.append({'scene': current_scene, 'stack': current_stack})

    hours = []

    first = True

    for i in range(DELAY[last_schedule.day.day]['nb']):
        hour = float(i) / 2 + DELAY[last_schedule.day.day]['start'] - 0.5
        if int(hour) == hour and not first:
            hours.append(int(hour))
        else:
            hours.append('')
        first = False

    return render_to_response('schedule/schedule.html',
                              {'day': schedule.day,
                               'stacks': stacks,
                               'hours': hours},
                              context_instance=RequestContext(request))
